import { FC, useEffect, useRef } from "react";
import { useScrollTemplateReducer } from "./useScrollReducer";

const Scroll: FC = () => {
    const [state, dispatch] = useScrollTemplateReducer();
    const refA = useRef<HTMLDivElement>(null);
    const refB = useRef<HTMLDivElement>(null);
    const refC = useRef<HTMLDivElement>(null);
    const observerRef = useRef<IntersectionObserver | null>(null);

    useEffect(() => {
      window.scrollTo({ top: 0, behavior: 'smooth'});
    }, []);

    useEffect(() => { 
        const handleIntersection = (entries: IntersectionObserverEntry[]) => {
            entries.forEach(entry => {
                if (entry.target === refA.current) {
                    if (entry.isIntersecting ) {
                        dispatch({ type: 'SET_TEMPLATE_TYPE', payload: 'A' });
                    }
                } else if (entry.target === refB.current) {
                    if (entry.isIntersecting) {
                        dispatch({ type: 'SET_TEMPLATE_TYPE', payload: 'B' });
                    }
                }
                else if (entry.target === refC.current) {
                    if (entry.isIntersecting) {
                        dispatch({ type: 'SET_TEMPLATE_TYPE', payload: 'C' });
                    }
                }
            });
        };

        // 创建观察者
        const observer = new IntersectionObserver(handleIntersection, {
            root: null,
            rootMargin: '0px',
            threshold: 0.1 // 10% 可见性阈值
        });

        // 观察两个模板
        if(refA.current){
            observer.observe(refA.current);
        }
        if(refB.current){
            observer.observe(refB.current);
        }
        if(refC.current){
            observer.observe(refC.current);
        }

        observerRef.current = observer;

        return () => {
            observer.disconnect();
        };
    }, []);



    return (
        <div >
            <h1>{state.templateType}</h1>
            <div ref={refA} style={{ height: '1500px', background: '#678921', color:'#fff', width:'80vw', borderRadius: '1rem' , display:'flex', alignItems:'center',justifyContent:'center'}}>
                <h1>Template A</h1>
            </div>

            <div ref={refB} style={{ height: '1200px', background: '#123456', color:'#fff', width:'80vw',marginTop: '50px' , borderRadius: '1rem' , display:'flex', alignItems:'center',justifyContent:'center'}}>
                <h1>Template B</h1>
            </div>
            <h1>{state.templateType}</h1>


            <div ref={refC} style={{ height: '1200px', background: '#654321',color:'#fff', width:'80vw',marginTop: '50px' , borderRadius: '1rem' , display:'flex', alignItems:'center',justifyContent:'center'}}>
                <h1>Template C</h1>
            </div>
            <h1>{state.templateType}</h1>

        </div>
    );
};

export default Scroll;